package com.freight.order.serviceimpl;

import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.entity.User;
import com.freight.core.service.UserService;
import com.freight.msg.entity.Message;
import com.freight.msg.entity.MessageSend;
import com.freight.msg.service.MessageSendService;
import com.freight.msg.service.MessageService;
import com.freight.msg.utils.MyJPushClient;
import com.freight.order.dao.*;
import com.freight.order.dto.QuotationDto;
import com.freight.order.entity.*;
import com.freight.order.mapper.*;
import com.freight.order.service.DriverQuotationRecordService;
import com.freight.order.vo.QuotationRecordVo;

import com.freight.user.entity.VehicleLicense;
import com.freight.user.mapper.DriverVoMapper;
import com.freight.user.mapper.VehicleVoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Slf4j
@Service
@Transactional
public class DriverQuotationRecordServiceImpl implements DriverQuotationRecordService {

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private MessageService messageService;

    @Autowired
    private QuotationRecordDao quotationRecordDao;

    @Autowired
    private QuotationDetailsDao quotationDetailsDao;

    @Autowired
    private OrderGoodsDao orderGoodsDao;

    @Autowired
    private QuotationRecordMapper quotationRecordMapper;

    @Autowired
    private HistoricalRecordsMapper historicalRecordsMapper;

    @Autowired
    private HistoricalRecordsDao historicalRecordsDao;

    @Autowired
    private OrderMainMapper orderMainMapper;

    @Autowired
    private OrderGoodsVoMapper orderGoodsVoMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private VehicleVoMapper vehicleVoMapper;

    @Autowired
    private GoodsLoadingTimeDao goodsLoadingTimeDao;

    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private DriverVoMapper driverVoMapper;

    @Override
    public QuotationRecordVo driverQuotationState(Long orderGoodsId) {

        User u = securityUtil.getCurrUser();

        List<HistoricalRecords> list = historicalRecordsMapper.getHistoricalRecords(u.getId(),orderGoodsId);

        if (list==null || list.size()==0){
            //添加找货记录
            HistoricalRecords historicalRecords=new HistoricalRecords();
            historicalRecords.setUserId(u.getId());
            historicalRecords.setRecordsId(orderGoodsId);
            historicalRecordsDao.save(historicalRecords);
        }else {
            HistoricalRecords historicalRecords=list.get(0);
            historicalRecordsDao.save(historicalRecords);
        }

        return quotationRecordMapper.driverQuotationState(orderGoodsId,u.getId());
    }

    @Override
    public List<QuotationDetails> quotationModifyList(Long quotationId) {

        User u = securityUtil.getCurrUser();

        Specification specification = new Specification<QuotationDetails>() {
            @Override
            public Predicate toPredicate(Root<QuotationDetails> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Long> quotationRecordId = root.get("quotationRecordId");
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(cb.equal(quotationRecordId, quotationId));
                Predicate[] arr = new Predicate[list.size()];
                return query.where(list.toArray(arr)).getRestriction();
            }
        };
        return quotationDetailsDao.findAll(specification);
    }

    @Override
    public List<QuotationRecordVo> driverQuotationRecord(Long orderGoodsId) {
        User user=securityUtil.getCurrUser();

        return quotationRecordMapper.driverRecord(orderGoodsId,user.getId());
    }


    @Override
    public void addQuotationRecord(QuotationDto quotationDto) {
        User user=securityUtil.getCurrUser();
        QuotationRecord quotationRecord=new QuotationRecord();
        quotationRecord.setOrderSource("2");
        if(user.getUserType()==1){
            quotationDto.setUserId(user.getId());
            quotationRecord.setOrderSource("1");
        }
        User u = userService.get(quotationDto.getUserId());
        if(u.getStatus() != 0){
            throw new FreightException("驾驶员账号被禁用");
        }
        VehicleLicense vehicleLicense = vehicleVoMapper.getVehicleLicenseUserId(quotationDto.getUserId());
        if(vehicleLicense.getGpsEquipment()==null || vehicleLicense.getGpsEquipment().equals("")){
            throw new FreightException("请先绑定车辆GPS设备号");
        }
        if(vehicleLicense==null || vehicleLicense.getRegistStatus()==0){
            throw new FreightException("请先认证车辆资料");
        }
        if(vehicleLicense==null || vehicleLicense.getRegistStatus()==2){
            throw new FreightException("耐心等待车辆资料审核");
        }
        QuotationDetails quotationDetails=new QuotationDetails();
        OrderGoods orderGoods=orderGoodsDao.getOne(quotationDto.getGoodsId());
        if(orderGoods!=null && orderGoods.getStatus()!=3){
            throw new FreightException("货源当前无法抢单");
        }
//        List<Long> orderId=orderMainMapper.getHangintheairOrder(quotationDto.getUserId());
//        if(orderId!=null && orderId.size() > 0){
//            throw new FreightException("该司机当前有正在执行的运单");
//        }

        if(!orderGoods.getGoodType().equals(vehicleLicense.getVehicleType())){
            throw new FreightException("货源类型和车辆可拉类型不一致");
        }

        List<QuotationRecord> list = quotationRecordMapper.getQuotationRecordList(orderGoods.getId(),quotationDto.getUserId());
        if(quotationDto.getQuotationRecordId()==null&&list!=null&&list.size()>0){
            throw new FreightException("该货源有待委托记录，请勿重复抢单");
        }

        List<GoodsLoadingTime> goodsLoadingList = orderGoodsVoMapper.getGoodsLoadingTime(quotationDto.getGoodsId(),quotationDto.getLoadingTime());
        if(goodsLoadingList==null || goodsLoadingList.size()==0){
            throw new FreightException("货源该时间段无法装车");
        }

        if(quotationDto.getQuotationRecordId()!=null && quotationDto.getQuotationRecordId()>0){
            quotationRecord=quotationRecordDao.getOne(quotationDto.getQuotationRecordId());
            if(quotationRecord.getDriverState().equals("2")){
                throw new FreightException("抢单记录已委托，不可修改装车时间");
            }
            if(quotationRecord.getDriverState().equals("3")){
                throw new FreightException("抢单记录已取消，不可修改装车时间");
            }

            List<QuotationDetails> detailsList = quotationRecordMapper.getQuotationDetails(quotationDto.getQuotationRecordId());
            if(detailsList!=null && detailsList.size()>0){
                QuotationDetails qd = detailsList.get(0);
                List<GoodsLoadingTime> goodsLoadingTimeList = orderGoodsVoMapper.obtainGoodsLoadingTime(quotationRecord.getOrderGoodsId(),qd.getLoadingTime());
                if(goodsLoadingTimeList!=null && goodsLoadingTimeList.size()>0){
                    GoodsLoadingTime goodsLoadingTime = goodsLoadingTimeList.get(0);
                    goodsLoadingTime.setLoadingState("1");
                    goodsLoadingTimeDao.save(goodsLoadingTime);
                }
            }
        }else {
            quotationRecord.setOrderGoodsId(quotationDto.getGoodsId());
            quotationRecord.setUserId(quotationDto.getUserId());
        }

        quotationRecord.setDriverState("1");
        quotationRecord=quotationRecordDao.save(quotationRecord);
        ObjectUtil.copyPropertiesIgnoreNull(quotationDto,quotationDetails);
        quotationDetails.setQuotationRecordId(quotationRecord.getId());
        quotationDetailsDao.save(quotationDetails);
        GoodsLoadingTime goodsLoadingTime=goodsLoadingList.get(0);
        goodsLoadingTime.setLoadingState("2");
        goodsLoadingTimeDao.save(goodsLoadingTime);

        if(user.getUserType()==1){

            Message message = new Message();
            message.setTitle("抢单消息");
            String content="司机"+user.getNickName()+"提交了抢单记录，货源编号为："+orderGoods.getGoodNo()+",请尽快处理。";

            message.setType("5");
            message.setTopicId("5");
            message.setContent(content);
            message.setUserId(orderGoods.getCompanyUserId());
            message=messageService.save(message);

            MessageSend messageSend=new MessageSend();
            messageSend.setUserId(orderGoods.getCompanyUserId());
            messageSend.setMessageId(message.getId());
            messageSend.setType("5");
            messageSendService.save(messageSend);

        }

    }

    @Override
    public void cancelQuotationRecord(Long quotationRecordId) {
        QuotationRecord quotationRecord=quotationRecordDao.getOne(quotationRecordId);

        List<QuotationDetails> details=quotationRecordMapper.getQuotationDetails(quotationRecord.getId());
        if(details == null || details.size()==0){
            throw new FreightException("操作出错");
        }
        User user = userService.get(quotationRecord.getUserId());
        OrderGoods orderGoods = orderGoodsDao.getOne(quotationRecord.getOrderGoodsId());
        QuotationDetails quotationDetails = details.get(0);
        quotationRecord.setDriverState("3");
        List<GoodsLoadingTime> goodsLoadingList = orderGoodsVoMapper.obtainGoodsLoadingTime(quotationRecord.getOrderGoodsId(),quotationDetails.getLoadingTime());
        if(goodsLoadingList!=null && goodsLoadingList.size()>0){
            GoodsLoadingTime goodsLoadingTime = goodsLoadingList.get(0);
            goodsLoadingTime.setLoadingState("1");
            goodsLoadingTimeDao.save(goodsLoadingTime);
            quotationRecordDao.save(quotationRecord);
        }

        String notificationTitle = "抢单取消";
        String msgTitle = "抢单取消";
        String msgContent = "您的抢单信息被取消了（"+orderGoods.getGoodNo()+"）";
        //极光推送
        MyJPushClient jPushUtil = new MyJPushClient();
        List<String> aliasList = Arrays.asList(user.getUsername());
        jPushUtil.sendToAliasList( aliasList,notificationTitle, msgTitle, msgContent, "3",null,null,null,-1);

    }

}
